//
//  HomeViewController.swift
//  KKWB
//
//  Created by KSY-iOS on 17/1/6.
//  Copyright © 2017年 KK. All rights reserved.
//

import UIKit
import MJRefresh

class HomeViewController: BaseViewController {
    
    //MARK:- 懒加载属性
    
    fileprivate lazy var titleBtn: TitleButton = TitleButton()
    fileprivate lazy var popoverAnimte: PopoverAnimate = PopoverAnimate {[weak self] (presented) in
        
        self?.titleBtn.isSelected = presented
    }
    
    fileprivate lazy var viewModels: [StatusViewModel] = [StatusViewModel]()
    fileprivate lazy var tipLabel : UILabel = UILabel()
    fileprivate lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
    override func viewDidLoad() {
        super.viewDidLoad()

        if !isLogin {
            // 没有登录
            visitorView.addRotationAnimation()
            return
        }
        
        // 设置导航栏的内容
        setupNavigationBar()
        
        setupRefreshView()
        setupFooterView()
        
        setupTipLabel()

        setupNotifications()
        
        tableView.estimatedRowHeight = 200
    }

    
}

// MARK:- 设置UI界面
extension HomeViewController {

    fileprivate func setupNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention");
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop");
        
        titleBtn.setTitle("新浪微博", for: .normal)
        titleBtn .addTarget(self, action: #selector(HomeViewController.titleBtnClick(_:)), for: .touchUpInside)
        
        navigationItem.titleView = titleBtn;
    }
    
    fileprivate func setupRefreshView() {
        
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewStatuses))
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("释放刷新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        
        tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
    }
    
    fileprivate func setupFooterView() {
      
        let footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreStatuses))
        tableView.mj_footer = footer
    }
    
    fileprivate func setupTipLabel() {
        // 1.将tipLabel添加父控件中
        navigationController?.navigationBar.addSubview(tipLabel)
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        
        // 2.设置tipLabel的frame
        tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
        
        // 3.设置tipLabel的属性
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 14)
        tipLabel.textAlignment = .center
        tipLabel.isHidden = true
    }
    
    fileprivate func setupNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(showPhotoBrowser), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
    }
}

// MARK:- 事件监听
extension HomeViewController {
    
    @objc fileprivate func titleBtnClick(_ titBtn: TitleButton) {
        
        titleBtn.isSelected = !titleBtn.isSelected
        
        let popVc = PopoverViewController()
        // 设置modal样式
        popVc.modalPresentationStyle = .custom
        // 
        popVc.transitioningDelegate = popoverAnimte
        //弹出vc
        present(popVc, animated: true, completion: nil)
    }
    
    @objc fileprivate func showPhotoBrowser(note : NSNotification) {
        // 0.取出数据
        let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! NSIndexPath
        let picURLs = note.userInfo![ShowPhotoBrowserUrlsKey] as! [NSURL]
        let object = note.object as! PicCollectionView
        
        // 1.创建控制器
        let photoBrowserVc = PhotoBrowserController(indexPath: indexPath as IndexPath, picURLs: picURLs as [URL])
        
        // 2.设置modal样式
        photoBrowserVc.modalPresentationStyle = .custom
        // 3.设置转场的代理
        photoBrowserVc.transitioningDelegate = photoBrowserAnimator
        
        // 4.设置动画的代理
        photoBrowserAnimator.presentedDelegate = object
        photoBrowserAnimator.indexPath = indexPath
        photoBrowserAnimator.dismissDelegate = photoBrowserVc
        // 以modal的形式弹出控制器
        present(photoBrowserVc, animated: true, completion: nil)
    }
}

// MARK:- 数据请求
extension HomeViewController {
    
    @objc fileprivate func loadNewStatuses() {
        
        loadStatus(isNewData: true)
    }
    
    @objc fileprivate func loadMoreStatuses() {
        
        loadStatus(isNewData: false)
    }
    
    fileprivate func loadStatus(isNewData : Bool) {
        
        // 1.获取since_id/max_id
        var since_id = 0
        var max_id = 0
        if isNewData {
            since_id = viewModels.first?.status?.mid ?? 0
        } else {
            max_id = viewModels.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        
        NetworkTools.shareInstance.loadStatus(since_id: since_id, max_id: max_id) { (result: [[String : AnyObject]]?, error: Error?) in
            if error != nil {
                return
            }
            
            guard let resultArray = result else {
                return
            }
            
            // 3.遍历微博对应的字典
            var tempViewModel = [StatusViewModel]()
            for statusDict in resultArray {
                let status = StatusModel(dict: statusDict)
                let viewModel = StatusViewModel(status: status)
                tempViewModel.append(viewModel)
            }
            
            // 4.将数据放入到成员变量的数组中
            if isNewData {
                self.viewModels = tempViewModel + self.viewModels
            } else {
                self.viewModels += tempViewModel
            }
            
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            self.showTipLabel(count: tempViewModel.count)
        }
    }
    
    private func showTipLabel(count: Int) {
        
        tipLabel.isHidden = false
        tipLabel.text = count == 0 ? "没有新数据" : "\(count) 条新数据"
        
        UIView.animate(withDuration: 1.0, animations: {
        
            self.tipLabel.frame.origin.y = 44
        }, completion: { (_) in
            
            UIView.animateKeyframes(withDuration: 1.0, delay: 1.0, options: [], animations: {
            
                self.tipLabel.frame.origin.y = 10
            }, completion: { (_) in
            
                self.tipLabel.isHidden = true
            })
        })
    }
}

// MARK:- tableview代理方法
extension HomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModels.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCellID") as! HomeViewCell
        
        cell.viewModel = viewModels[indexPath.row]
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return viewModels[indexPath.row].cellHeight
    }
}
